package cn.butcher21.controller;

import cn.butcher21.dao.DaoUser;
import cn.butcher21.dao.DaoWorkImpl.DaoUserImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "CheckCookieServlet", value = "/checkCookie")
public class CheckCookieServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        if (session.getAttribute("userid") != null) {
            response.sendRedirect("index.html");
            return;
        }
        Cookie[] cookies = request.getCookies();
        String username = "";
        String password = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                System.out.println(cookie.getName() + "=" + cookie.getValue());
                if (cookie.getName().equals("username")) username = cookie.getValue();
                if (cookie.getName().equals("password")) password = cookie.getValue();
            }

        }

        DaoUser daoUser = new DaoUserImpl();
        try {
            String[] check = daoUser.check(username, password);
            if (check != null) {
                session.setAttribute("userid", check[0]);
                response.sendRedirect("index.html");
            } else {
                response.sendRedirect("login.html");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
